package com.junzhiit.nengji.cms.config;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.junzhiit.nengji.cms.web.vo.BaseValueObject;

@Aspect
@Component
public class ValueObjectAspect {

	@Pointcut(value = "execution(* com.junzhiit.nengji.cms.web.controller..*.*(..))")
	public void executeController() {
	}

	// 把VO类中String类型的参数的"NULL","null"转换为值
	@Before(value = "executeController()")
	public void doBefore(JoinPoint joinPoint) {
		Object[] objArr = joinPoint.getArgs();
		for (int i = 0; i < objArr.length; i++) {
			if (objArr[i] instanceof BaseValueObject) {
				Object obj = joinPoint.getArgs()[i];
				Class<? extends Object> classz = obj.getClass();
				Field[] fields = classz.getDeclaredFields();
				for (Field field : fields) {
					if (String.class == field.getType()) {
						char[] cs = (field.getName()).toCharArray();
						cs[0] -= 32;
						String methodGetName = "get" + String.valueOf(cs);
						String methodSetName = "set" + String.valueOf(cs);
						try {
							Method getMethod = classz.getMethod(methodGetName, null);
							Method setMethod = classz.getMethod(methodSetName, String.class);
							String value = (String) getMethod.invoke(obj, null);
							if ("NULL".equals(value) || "null".equals(value)) {
								setMethod.invoke(obj,(Object)null);
							}
						} catch (NoSuchMethodException | SecurityException | IllegalArgumentException
								| InvocationTargetException | IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
